package com.gingko.duominuo.network

import com.gingko.duominuo.BuildConfig
import com.gingko.duominuo.network.api.GinkgoService
import com.gingko.duominuo.network.interceptor.CommonParamsInterceptor
import com.itkacher.okhttpprofiler.OkHttpProfilerInterceptor
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ApplicationComponent
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.inject.Singleton

@Module
@InstallIn(ApplicationComponent::class)
object NetworkModule {
    private const val TIME_OUT = 15L
    private val downloadRetrofit by lazy {
        val builder = OkHttpClient.Builder().connectTimeout(TIME_OUT, TimeUnit.SECONDS)
        Retrofit.Builder()
            .baseUrl(BuildConfig.BASE_URL)
            .client(builder.build())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    @Singleton
    @Provides
    fun provideUserService(retrofit: Retrofit): GinkgoService =
        retrofit.create(GinkgoService::class.java)


    @Singleton
    @Provides
    fun provideRetrofit(okHttp: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .baseUrl(BuildConfig.BASE_URL)
            .client(okHttp)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    @Singleton
    @Provides
    fun provideOkHttpClient(): OkHttpClient {
        val builder = OkHttpClient.Builder()
        val logging = HttpLoggingInterceptor()
        if (BuildConfig.DEBUG) {
            logging.level = HttpLoggingInterceptor.Level.BODY
            builder.addInterceptor(OkHttpProfilerInterceptor())
        } else {
            logging.level = HttpLoggingInterceptor.Level.BASIC
        }
        if (BuildConfig.DEBUG) {
            builder.addInterceptor(OkHttpProfilerInterceptor())
        }
        builder
//            .addInterceptor(logging)
            .addInterceptor(CommonParamsInterceptor())
            .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
        return builder.build()
    }
}
